<template>
  <!-- 新增党员模态框 -->
  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card 
      style="width: 600px" 
      title="新增党员" 
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <template #header-extra>
        <n-button quaternary circle @click="handleClose">
          <template #icon>
            <n-icon><CloseIcon /></n-icon>
          </template>
        </n-button>
      </template>

      <n-form 
        ref="formRef" 
        :model="form" 
        :rules="formRules"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
      >
        <n-form-item path="memberName" label="姓名">
          <n-input
            v-model:value="form.memberName"
            placeholder="请输入姓名"
            clearable
          />
        </n-form-item>
        
        <n-form-item path="studentId" label="学号">
          <n-input
            v-model:value="form.studentId"
            placeholder="请输入学号"
            clearable
          />
        </n-form-item>
        
        <n-form-item path="idCardNumber" label="身份证号">
          <n-input
            v-model:value="form.idCardNumber"
            placeholder="请输入身份证号"
            clearable
            maxlength="18"
          />
        </n-form-item>
        
        <n-form-item path="phoneNumber" label="手机号">
          <n-input
            v-model:value="form.phoneNumber"
            placeholder="请输入手机号"
            clearable
            maxlength="11"
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space justify="end">
          <n-button @click="handleClose">取消</n-button>
          <n-button type="primary" @click="handleSubmit" :loading="loading">
            确认新增
          </n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import {
  NModal, NCard, NForm, NFormItem, NInput, NButton, NIcon, NSpace
} from 'naive-ui'
import { X as CloseIcon } from '@vicons/tabler'
import { createMember } from '@/api'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:show', 'success'])

// 响应式数据
const showModal = computed({
  get: () => props.show,
  set: (value) => emit('update:show', value)
})

const loading = ref(false)
const formRef = ref(null)
const form = ref({
  memberName: '',
  studentId: '',
  idCardNumber: '',
  phoneNumber: ''
})

// 表单验证规则
const formRules = {
  memberName: [
    { required: true, message: '请输入姓名', trigger: ['input', 'blur'] },
    { min: 2, max: 20, message: '姓名长度应为2-20个字符', trigger: ['input', 'blur'] }
  ],
  studentId: [
    { required: true, message: '请输入学号', trigger: ['input', 'blur'] },
    { pattern: /^[A-Za-z0-9]+$/, message: '学号只能包含字母和数字', trigger: ['input', 'blur'] }
  ],
  idCardNumber: [
    { required: true, message: '请输入身份证号', trigger: ['input', 'blur'] },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号格式', trigger: ['input', 'blur'] }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: ['input', 'blur'] },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: ['input', 'blur'] }
  ]
}

// 方法
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    await createMember(form.value)
    emit('success')
    handleClose()
  } catch (error) {
    console.error('新增党员失败:', error)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  showModal.value = false
}

const resetForm = () => {
  form.value = {
    memberName: '',
    studentId: '',
    idCardNumber: '',
    phoneNumber: ''
  }
  formRef.value?.restoreValidation()
}

// 监听模态框关闭，重置表单
watch(showModal, (newValue) => {
  if (!newValue) {
    resetForm()
  }
})
</script>